package com.haohan.cloud.scm.supply.core.impl;

import cn.hutool.core.bean.BeanUtil;
import com.haohan.cloud.scm.api.manage.entity.UPassport;
import com.haohan.cloud.scm.api.manage.feign.UPassportFeignService;
import com.haohan.cloud.scm.api.supply.entity.Supplier;
import com.haohan.cloud.scm.common.tools.exception.ErrorDataException;
import com.haohan.cloud.scm.common.tools.util.RUtil;
import com.haohan.cloud.scm.supply.core.IScmSupplyInfoService;
import com.haohan.cloud.scm.supply.service.SupplierService;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.common.core.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author dy
 * @date 2019/6/10
 */
@Service
public class ScmSupplyInfoServiceImpl implements IScmSupplyInfoService {

    @Autowired
    @Lazy
    private UPassportFeignService uPassportFeignService;
    @Autowired
    @Lazy
    private SupplierService supplierService;

    /**
     * 新增供应商
     * @param supplier
     *      必需参数: telephone/ SupplierName
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Supplier add(Supplier supplier) {
        // 绑定通行证
        UPassport uPassport = new UPassport();
        uPassport.setTelephone(supplier.getTelephone());
        uPassport.setLoginName(supplier.getSupplierName());
        R r = uPassportFeignService.add(uPassport, SecurityConstants.FROM_IN);
        if (!RUtil.isSuccess(r)) {
            throw new ErrorDataException(r.getMsg());
        }
        uPassport = BeanUtil.toBean(r.getData(), UPassport.class);
        if (null == uPassport) {
            throw new ErrorDataException("uPassport为空");
        }
        supplier.setPassportId(uPassport.getId());
        supplierService.save(supplier);
        return supplier;
    }

}
